package org.bdware.irs.server.http;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.apache.cxf.helpers.IOUtils;
import org.json.JSONObject;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public abstract class RegisterHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange exchange) {
        Map<String,String> respMap;
        try{
            //获得表单提交数据(post)
            String postString = IOUtils.toString(exchange.getRequestBody());
            Map<String,String> postInfo = formData2Dic(postString);
            respMap = HandleRequest(postInfo);
            JSONObject jsonObj=new JSONObject(respMap);
            exchange.getResponseHeaders().add("Access-Control-Allow-Origin","*");
            exchange.sendResponseHeaders(200,0);
            OutputStream os = exchange.getResponseBody();
            os.write(jsonObj.toString().getBytes());
            os.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public abstract Map<String,String> HandleRequest(Map<String, String> postInfo);

    public Map<String,String> formData2Dic(String formData ) {
        Map<String,String> result = new HashMap<>();
        if(formData== null || formData.trim().length() == 0) {
            return result;
        }
        final String[] items = formData.split("&");
        Arrays.stream(items).forEach(item ->{
            final String[] keyAndVal = item.split("=");
            if( keyAndVal.length == 2) {
                try{
                    final String key = URLDecoder.decode( keyAndVal[0],"utf8");
                    final String val = URLDecoder.decode( keyAndVal[1],"utf8");
                    result.put(key,val);
                }catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
        return result;
    }

    public String geneRandomID(){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<10;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
